package com.example.retrofit;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class Main3Activity extends AppCompatActivity {
    private Timer mTimer = null;
    private TextView send_tv;
    private int countdown = 10;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        send_tv = (TextView) findViewById(R.id.textView2);
        //点击事件
        send_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTimer();
            }
        });
    }
    //开始倒计时
    private void startTimer() {
        //点击获取验证码后改变按钮的状态,让按钮不可点击
        send_tv.setClickable(false);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1);
            }
        }, 0, 3000);
    }



    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            send_tv.setText(countdown + "秒");
            send_tv.setAlpha(0.5f);
            if (0 == countdown) {
                //停止倒计时显示页面
                resume();
                stopTimer();

                return;
            }
            countdown--;

        }
    };

    private void resume() {
        stopTimer();
        countdown =  100;
        //倒计时结束后,让按钮重新可点击
        send_tv.setClickable(true);
        send_tv.setText("重发");
        send_tv.setAlpha(0.9f);
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
